package org.lqfan.service.impl;

import org.lqfan.dao.OrderDOMapper;
import org.lqfan.dataobject.OrderDO;
import org.lqfan.error.BusinessException;
import org.lqfan.error.EmBusinessError;
import org.lqfan.service.ItemService;
import org.lqfan.service.OrderService;
import org.lqfan.service.UserService;
import org.lqfan.service.model.ItemModel;
import org.lqfan.service.model.OrderModel;
import org.lqfan.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;

public class OrderServiceImpl implements OrderService {

    @Autowired
    private ItemService itemService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDOMapper orderDOMapper;


    @Override
    public OrderModel createOrder(Integer itemId, Integer userId, Integer amount) throws BusinessException {
        //1.校验下单状态，下单的商品是否存在，用户是否合法，购买数量是否正确
        ItemModel itemModel = itemService.getItemById(itemId);
        if(itemModel == null) {
            throw new BusinessException(EmBusinessError.ITEM_NOT_EXIST);
        }

        UserModel userModel = userService.getUserById(userId);
        if(userModel == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }

        if(amount <=0 || amount >99) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "数量不正确");
        }

        //2.落单减库存
        boolean result = itemService.decreaseStock(itemId, amount);
        if(!result) {
            throw new BusinessException(EmBusinessError.STOCK_NOT_ENOUGH);
        }

        //3.订单入库
        OrderModel orderModel = new OrderModel();
        orderModel.setAmount(amount);
        orderModel.setItemId(itemId);
        orderModel.setUserId(userId);
        orderModel.setItemPrice(itemModel.getPrice());
        orderModel.setOrderPrice(itemModel.getPrice().multiply(new BigDecimal(amount)));

        //生成订单号（流水号）

        OrderDO orderDO = this.convertDOFromModel(orderModel);
        orderDOMapper.insertSelective(orderDO);

        //4.返回前端
        return null;
    }

    private OrderDO convertDOFromModel(OrderModel orderModel) {
        OrderDO orderDO = new OrderDO();
        BeanUtils.copyProperties(orderModel, orderDO);

        return orderDO;
    }
}
